<?php
/**
 *  DIC configuration
 * @var $app        \slimExt\base\App
 * @var $config     \slimExt\DataCollector
 * @var $container  \slimExt\base\Container
 * @return mixed
 */


// custom request service {@see \Slim\DefaultServicesProvider::register()}
$container['request'] = function($c){
    /** @var $c slimExt\base\Container */
    return \slimExt\base\Request::createFromEnvironment($c->get('environment'));
};
    // custom response service {@see \Slim\DefaultServicesProvider::register()}
$container['response'] = function($c){
    /** @var $c slimExt\base\Container */
    $headers  = new \Slim\Http\Headers([
        'Content-Type' => 'text/html; charset=' . $c->get('settings')['charset']
    ]);
    $response = new \slimExt\base\Response(200, $headers);

    return $response->withProtocolVersion($c->get('settings')['httpVersion']);
};

// project language config
$container['language'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $options = $c->get('settings')['language'];

    return new \slimExt\base\Language($options);
};

// project login user identity
$container['user'] = function ($c) {
    /** @var $c slimExt\base\Container */
    return new \slimExt\base\User($c->settings->get('user'));
};

// ...
$container['accessChecker'] = function ($c) {
    /** @var $c slimExt\base\Container */
    return new \slimExt\base\AccessChecker();
};

// monolog - request logger
$container['logger'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $settings = $c->get('settings')['logger'];
    $logger = new \Monolog\Logger($settings['name']);
    $logger->pushProcessor(new \Monolog\Processor\UidProcessor());
    $logger->pushHandler(new \Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG));
    return $logger;
};

// monolog - database logger
$container['dbLogger'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $settings = $c->get('settings')['dbLogger'];
    $logger = new \Monolog\Logger($settings['name']);
    // $logger->pushProcessor(new \Monolog\Processor\UidProcessor());
    $handler = new \Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG);
    // formatter, ordering log rows
    $handler->setFormatter(new \Monolog\Formatter\LineFormatter("[%datetime%] SQL: %message% \n"));
    $logger->pushHandler($handler);
    return $logger;
};

// monolog - database logger
$container['eventLogger'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $settings = $c->get('settings')['eventLogger'];
    $logger = new \Monolog\Logger($settings['name']);
    // $logger->pushProcessor(new \Monolog\Processor\UidProcessor());
    $handler = new \Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG);
    // formatter, ordering log rows
    $handler->setFormatter(new \Monolog\Formatter\LineFormatter("[%datetime%] %message% %context% \n"));
    $logger->pushHandler($handler);

    return $logger;
};

// monolog - error logger
$container['errLogger'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $settings = $c->get('settings')['errLogger'];
    $logger = new \Monolog\Logger($settings['name']);

    $handler = new \Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG);
    // formatter, ordering log rows
    $handler->setFormatter(new \Monolog\Formatter\LineFormatter("[%datetime%] %message% %context% \n"));

    $logger->pushHandler($handler);

    return $logger;
};

// Register csrf Guard
$container['csrf'] = function () {
    return new \Slim\Csrf\Guard;
};

// Register flash message provider
$container['flash'] = function () {
    return new \Slim\Flash\Messages();
};

// php view renderer
$container['renderer'] = function ($c) {
    /** @var $c slimExt\base\Container */
    $settings = $c->get('settings')['renderer'];
    return new \Slim\Views\PhpRenderer($settings['template_path']);
};

// override default service

$container['notFoundHandler'] = function () use ($config) {
    $viewFile = Slim::alias($config->get('pages.notFound'));

    return new \slimExt\handlers\NotFound($viewFile,null, [
        'searchUrl' => $config->get('urls.search'),
    ]);
};

//
$container['runExceptionHandler'] = function ($app, $config, \Exception $e) {

    /**
     * @var $app    \slimExt\base\App
     * @var $config \slimExt\DataCollector
     * @var $e      \inhere\librarys\exceptions\BaseException
     */

    // If app debug is opening.
    if ( $config->get('debug', false) ) {
        throw $e;
    }

    // Log the error message
    $text = ($msg = $e->getMessage()) . '. At ' . $e->getFile() . '. Line ' . $e->getLine();
    // $text .= $exception->getTraceAsString();

    Slim::get('errLogger')->error($text, [
        'Uri' => $app->request->getRequestTarget()
    ]);

    // If is a user notice message.
    if ( property_exists($e, 'isVisible') && $e->isVisible ) {
        // json

        // html
        // when is xhr
        if ( $app->request->isXhr() ) {
            $response = $app->response->withJson($e->getCode(), $msg);
        } else {
            $response = $app->response->withMessage($msg)->withRedirect($config->get('urls.home'));
        }

        $app->respond($response);
    }

    exit(0);
};
